
#include "libs/libdef.h"

inline void print_read_msg(const sockaddr_in & addr, const std::string & msg) {
    std::cout
            << "read from server "
            << inet_ntoa(addr.sin_addr) << ":" << ntohs(addr.sin_port)
            << " <" << msg << ">"
            << std::endl;
}

int client(int srv_port, const std::string & srv_host) {
    int READ_BUF_SIZE = 2048;

    int cli_sock = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in srv_addr { };
    memset(&srv_addr, 0, sizeof(srv_addr));
    srv_addr.sin_port = htons(srv_port);
    srv_addr.sin_addr.s_addr = inet_addr(srv_host.c_str());
    srv_addr.sin_family = AF_INET;

    if (connect(cli_sock, (sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) {
        close(cli_sock);
        EXIT_ERR(strerror(errno));
    }

    char read_buf[READ_BUF_SIZE];

    std::string msg;
    while (getline(std::cin, msg)) {
        if (msg.empty()) continue;
        msg.insert(0, "C");
        write(cli_sock, msg.c_str(), msg.size());

        std::string read_msg;
        int read_len = read(cli_sock, read_buf, READ_BUF_SIZE);
        read_msg.append(read_buf, read_len);

        print_read_msg(srv_addr, read_msg);
    }

    close(cli_sock);

    return 0;
}

int main(int argc, char** argv) {

    int port = 4399;
    std::string host = "192.168.64.2";

    if (client(port, host) < 0) LOG_ERR(strerror(errno));

    return 0;
}
